package com.zhzj.activity;

import android.annotation.TargetApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.zhzj.R;
import com.zhzj.interfaces.SonicRuntimeImpl;
import com.zhzj.interfaces.SonicSessionClientImpl;
import com.zhzj.utils.StatusBarUtil;
import com.zhzj.widget.MyWebView;

public class MainActivity extends AppCompatActivity {

    private String mLoginIndex = "http://wxqts.dg.cn/ydd/a/login";
    private String mHomeIndex = "http://wxqts.dg.cn/ydd/a/app/agendaItem/index";
    private String mWorkIndex = "http://wxqts.dg.cn/ydd/a/app/work/index";
    private String mContactsIndex = "http://wxqts.dg.cn/ydd/a/app/contacts/index";
    private String mInfoIndex = "http://wxqts.dg.cn/ydd/a/app/appUser/userInfo";
    private SonicSession sonicSession;
    private MyWebView mWebView;
    private boolean mBackPressedTag = false;
//    private View mLoadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        SonicSessionClientImpl sonicSessionClient = null;
        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(mLoginIndex, new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
//            throw new UnknownError("create session fail!");
            Log.e("lzr", "创建失败");
        }

        // step 3: BindWebView for sessionClient and bindClient for SonicSession
        // in the real world, the init flow may cost a long time as startup
        // runtime、init configs....

        setContentView(R.layout.activity_main);
        StatusBarUtil.setColorNoTranslucent(this, ContextCompat.getColor(this, R.color.colorAccent));
        mWebView = (MyWebView) findViewById(R.id.main_webview_content);
//        mLoadingView =  findViewById(R.id.main_loading_view);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    //step 6: Call sessionClient.requestResource when host allow the application
                    // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });
        //对不同版本浏览器核心选择图片进行适配
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
//                if (newProgress == 100) {
//                    mLoadingView.setVisibility(View.GONE);
//                } else {
//                    mLoadingView.setVisibility(View.VISIBLE);
//                }
            }
        });

        WebSettings webSettings = mWebView.getSettings();

        // step 4: bind javascript
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
//        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
//        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
//        mWebView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");
        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        // step 5: webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(mWebView);
            sonicSessionClient.clientReady();
        } else { // default mode
            mWebView.loadUrl(mLoginIndex);
        }
    }

    @Override
    public void onBackPressed() {
        Log.e("lzr","网址："+mWebView.getUrl());
        if (mWebView.canGoBack()) {
            if (mWebView.getUrl().equals(mLoginIndex) || mWebView.getUrl().equals(mHomeIndex) ||
            mWebView.getUrl().equals(mWorkIndex) || mWebView.getUrl().equals(mContactsIndex) ||
                    mWebView.getUrl().equals(mInfoIndex)) {
                if (mBackPressedTag) {
                    super.onBackPressed();
                } else {
                    mBackPressedTag = true;
                    Toast.makeText(MainActivity.this, "再按一次将退出应用", Toast.LENGTH_SHORT).show();
                    new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mBackPressedTag = false;
                        }
                    }.start();
                }
            } else {
                mWebView.goBack();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }


}
